/**
 * Created by   : HuXiaoting
 * Created time : 2017/3/21
 * File explain : 材料-登录页面交互JS文件
 */
require.config({
  baseUrl: "../../libs",
  paths: {
    pubconfig: ['../paycenter'],
    jquery: ["jquery/jquery-1.11.3"],
    comConfig: ["../common/js/common-config"],
    static: ["static/tools/gt"],
    vue: ["./vue2-4-1/vue"],
    qrcode: ["jquery.qrcode.min"],
    MD5:["md5/md5"]
  }
});

require(["jquery", "pubconfig"], function () {
  window.sessionStorage.clear();
  sessionStorage.setItem('seller-center-project', JSON.stringify(pubconfig));
  require(["MD5","vue", "comConfig", "static"], operationCodeFun);
});

function operationCodeFun(md5,Vue) {
  // 配置文件内容
  var QHConfig = $("body").data("config");

  //变量声明
  var keyWord = null;//获取ajax的head验证码参数


  //getKeyWordByServer();


  var userNameReg = QHConfig.testReg.phoneReg;
  var passWordReg = /^[0-9A-Za-z]{6,20}$/;//6到20位数字字母组合

  var tips = [
    "您输入的密码与手机号不匹配，请重新输入",
    "验证失败",
    "您的账号已被禁用，如有问题请拨打：0571-81608755",
    "请输入用户名",
    "密码不能为空",
    "密码不正确",
    "您输入的手机号有误，请重新输入"
  ];

  var loginMain = new Vue({
    el: "#login-main",
    data: {
      userName: "",
      passWord: "",
      canClick: false,
      tip: "",
      err: false
    },
    methods: {
      login: function () {
        this.tip = "";
        this.err = false;
        var userInfo = null;//登录需要的用户信息
        $(".login-tip").addClass("hide");//每次点击都隐藏当前提示再判断
        //判断验证码
        if (keyWord == null) {
          this.tip = "请先完成滑块验证";
          this.err = true;
        }

          //手机用户信息
		  
          userInfo = {
            geetestChallenge:'1', //keyWord.challenge,
            geetestValidate:'2', //keyWord.validate,
            geetestSeccode:'3' //keyWord.seccode
          };
			
          userInfo = JSON.stringify(userInfo);
			
          this.getAjaxFun(userInfo);//登录请求

      },
      userNameTest: function () {
        var test = false;
        if (this.userName.length === 0) {
          this.tip = tips[3];
          this.err = true;
        } else {
          if (userNameReg.test(this.userName) == false) {
            this.tip = tips[6];
            this.err = true;
          } else {
            this.tip = "";
            this.err = false;
            test = true;
          }
        }
        return test;
      },
      passwordTest: function () {
        if (this.passWord.length === 0) {
          this.tip = tips[4];
          this.err = true;
        } else {
          if (passWordReg.test(this.passWord) == false) {
            this.tip = tips[5];
            this.err = true;
          } else {
            this.tip = "";
            this.err = false;
          }
        }
      },
      iptKeyup: function () {
        userNameReg.test(this.userName) && passWordReg.test(this.passWord)
          ? (this.canClick = true) : (this.canClick = false);
      },
      //调用登录ajax
      getAjaxFun: function (ajaxData) {
        var login = this;
		var opt={
          type: "POST",
          //url: QHConfig.url.login + "/" + login.userName + "/" + md5(login.passWord),
		  //url: "http://192.168.59.3:6091/Authority/send/paycenter/usercenter/payLogin/"+login.userName+"/"+md5(login.passWord)+"/1",
		  url: QHConfig.url.login,
		  data:{userName:login.userName,password:md5(login.passWord)},
          dataType: "json",
          success: function (data) {
			  console.log(JSON.stringify(data));
            var roles = {"6": "mater", "7": "equip", "8": "install"};
            if (data.status == 200) {
              $(".login-tip").addClass("hide");
              //判断是不是有storage功能
              if (typeof(Storage) !== "undefined") {
                sessionStorage.setItem("userInfo", JSON.stringify(data.data.list));
                sessionStorage.setItem('sellerToken', data.token);
				//只有一个角色时直接选择该角色
				
                if(data.data.list.length == 1){
					var info = data.data.list[0];
					var opts={
					type: "POST",
                    url: QHConfig.url.selectRole+"?userCode="+info.userCode,
                    data: ajaxData,
                    success: function(res){
					  console.log(JSON.stringify(res));
					  if(res.status==200){
						sessionStorage.setItem('sellerToken', res.token);
						sessionStorage.setItem("seller_role",roles[info.roleId]);
						location.href = "../../tpl/mdu-sxb-account/mdu-sxb-account.html"  
					  }
                    }
                  }
                  $.ajax(tokenAjax(opts));
                  return ;
                }
				//多个角色时跳转到角色选择
				location.href = "../choice-role/choice-role.html"
              } else {
                console.log("抱歉！您的浏览器不支持 Web Storage");
              }
            } else if (data.status == '400') {
              login.tip = data.message;
              login.err = true;
            }
          },
          error: function (err) {
			  console.log(JSON.stringify(err));
            login.tip = "网络错误";
            login.err = true;
          }
        }
        $.ajax(tokenAjax(opt));
      }
    }
  });


  //向服务器获取验证码
  function getKeyWordByServer() {
    var nowTime = (new Date()).getTime();//获取当前时间戳

    // 验证开始需要向网站主后台获取id，challenge，success（是否启用failback）
    $.ajax(tokenAjax({
      url: QHConfig.url.loginCode + nowTime, // 加随机数防止缓存
      type: "get",
      async: false,
      dataType: "json",
      success: function (data) {
        data = JSON.parse(data.data);
        // 使用initGeetest接口
        // 参数1：配置参数
        // 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
        initGeetest({
          gt: data.gt,
          challenge: data.challenge,
          product: "float", // 产品形式，包括：float，embed，popup。注意只对PC版验证码有效
          offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
          // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
        }, handlerPopup);
      }
    }));
  };

  //获取验证码成功回调
  function handlerPopup(captchaObj) {
    // 成功的回调
    captchaObj.onSuccess(function () {
      var validate = captchaObj.getValidate();//方法

      keyWord = {
        challenge: validate.geetest_challenge,
        validate: validate.geetest_validate,
        seccode: validate.geetest_seccode
      };//获取登录ajax的head参数

      userNameReg.test(loginMain.userName) && passWordReg.test(loginMain.passWord)
        ? (loginMain.canClick = true) : (loginMain.canClick = false);

    });
    // 将验证码加到id为popup-captcha的元素里
    captchaObj.appendTo("#popup-captcha");
  }
}
